package xuegao.study.mall.rbac.util;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import xuegao.study.mall.common.model.ums.UmsMenu;
import xuegao.study.mall.common.vo.ums.UmsMenuVo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MenuTreeUtils {

    public static List<UmsMenuVo> menusVoTree(List<UmsMenu> allMenus) {
        List<UmsMenuVo> voList = new ArrayList<>();
        if (allMenus == null || allMenus.size() == 0) {
            return voList;
        }
        Map<Integer, List<UmsMenu>> levelMap = allMenus.stream().collect(Collectors.groupingBy(UmsMenu::getLevel));
        List<UmsMenu> topMenus = levelMap.get(0);
        List<UmsMenu> childMenus = levelMap.get(1);
        Map<Long, List<UmsMenu>> childrenMenuMap = new HashMap<>();
        if (childMenus != null && childMenus.size() > 0) {
            childrenMenuMap = childMenus.stream().collect(Collectors.groupingBy(UmsMenu::getParentId));
        }
        for (UmsMenu menuItem : topMenus) {
            UmsMenuVo vo = new UmsMenuVo();
            BeanUtils.copyProperties(menuItem, vo);
            List<UmsMenu> umsMenus = childrenMenuMap.get(menuItem.getId());
            if (!CollectionUtils.isEmpty(umsMenus)) {
                List<UmsMenuVo> childrens = new ArrayList<>();
                for (UmsMenu item : umsMenus) {
                    UmsMenuVo voItem = new UmsMenuVo();
                    BeanUtils.copyProperties(item, voItem);
                    childrens.add(voItem);
                }
                vo.setChildren(childrens);
            }
            voList.add(vo);
        }
        return voList;
    }
}
